package com.dense.kuiniu.bookborrow.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import com.blankj.utilcode.util.SDCardUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import androidx.core.content.FileProvider;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


/**
 * @author Administrator
 * @date 2020/7/28
 */
public class InstallUtils {
    /**
     *      * 保存到本地
     *      *
     *      * @param context
     *      * @param fileName assets下的文件名
     *      * @param path     存储路径
     *     
     */
    public void copyApkFromAssets(Activity context, String fileName, InstallListener listener) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                try {
                    InputStream is = context.getAssets().open(fileName);
                    List<SDCardUtils.SDCardInfo> list = SDCardUtils.getSDCardInfo();
                    if (!list.isEmpty()) {
                        String dir = list.get(0).getPath() + "/kuiniu/apk/" + fileName;
                        File file = new File(dir);
                        if (!file.exists()) {
                            File parent = file.getParentFile();
                            if (parent != null && !parent.exists()) {
                                parent.mkdirs();  //创建所有父文件夹
                            }
                        } else {
                            file.delete();
                        }
                        file.createNewFile();
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] temp = new byte[1024];
                        int i = 0;
                        while ((i = is.read(temp)) > 0) {
                            fos.write(temp, 0, i);
                        }
                        fos.close();
                        is.close();
                        installApk(file, context);
                    }
                    emitter.onNext("安装完成");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        if (listener != null) {
                            listener.onComplete(s);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     *      * 安装apk （注意在安装apk时的Android7.0配置path的问题）
     *      *
     *      * @param file
     *      * @param c
     *     
     */
    private void installApk(File file, Activity c) {
        if (!file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(c, "com.dense.kuiniu.dense_frame.android7.fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        c.startActivityForResult(intent, 88);
    }

    public static interface InstallListener {
        public void onComplete(String msg);
    }
}
